<template>
  <el-alert
    v-if="visible"
    :title="title"
    :type="type"
    :closable="closable"
    show-icon
    @close="visible = false"
    class="global-notifier"
  />
</template>

<script setup>
import { ref, watch, defineProps, defineExpose } from 'vue';

const props = defineProps({
  title: {
    type: String,
    default: '',
  },
  type: {
    type: String,
    default: 'info', // 'success' | 'warning' | 'info' | 'error'
  },
  closable: {
    type: Boolean,
    default: true,
  },
  show: {
    type: Boolean,
    default: false,
  },
});

const visible = ref(props.show);

watch(() => props.show, (val) => {
  visible.value = val;
});

watch(() => props.title, (val) => {
  if (val) visible.value = true;
});

// 允许父组件通过ref调用显示/隐藏
function notify({ title, type = 'info', closable = true }) {
  notifier.title = title;
  notifier.type = type;
  notifier.closable = closable;
  visible.value = true;
}

const notifier = {
  title: props.title,
  type: props.type,
  closable: props.closable,
  notify,
};

defineExpose(notifier);
</script>

<style scoped>
.global-notifier {
  position: fixed;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 2000;
  min-width: 320px;
  max-width: 90vw;
}
</style>